package net.zoneland.knowledge.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 解决 EasyExcel 日期类型 LocalDateTime 转换的问题
 */
public class LocalDateTimeConverter implements Converter<LocalDateTime> {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateHelper.DEFAULT_DATE_FORMAT);

    @Override
    public Class<LocalDateTime> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(final ReadCellData cellData, final ExcelContentProperty contentProperty,
                                           final GlobalConfiguration globalConfiguration) {
        return LocalDateTime.parse(cellData.getStringValue(), formatter);
    }

    @Override
    public WriteCellData<String> convertToExcelData(final LocalDateTime value, final ExcelContentProperty contentProperty,
                                                    final GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(value.format(formatter));
    }

}
